package com.powerbank.adminsystem.controller;

import com.powerbank.adminsystem.entity.AdminUser;
import com.powerbank.adminsystem.service.AdminUserService;
import com.powerbank.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 管理员用户控制器
 */
@Tag(name = "管理员用户", description = "管理员用户相关接口")
@RestController
@RequestMapping("/api/admin/users")
@RequiredArgsConstructor
public class AdminUserController {

    private final AdminUserService adminUserService;

    @Operation(summary = "用户登录", description = "管理员用户登录")
    @PostMapping("/login")
    public Result<String> login(
            @Parameter(description = "用户名") @RequestParam String username,
            @Parameter(description = "密码") @RequestParam String password,
            HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        return adminUserService.login(username, password, ip);
    }

    @Operation(summary = "用户登出", description = "管理员用户登出")
    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String token) {
        return adminUserService.logout(token);
    }

    @Operation(summary = "获取当前用户信息", description = "根据Token获取当前用户信息")
    @GetMapping("/info")
    public Result<AdminUser> getCurrentUserInfo(@RequestHeader("Authorization") String token) {
        return adminUserService.getUserByToken(token);
    }

    @Operation(summary = "修改密码", description = "修改管理员密码")
    @PutMapping("/password")
    public Result<Void> changePassword(
            @RequestHeader("Authorization") String token,
            @Parameter(description = "旧密码") @RequestParam String oldPassword,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        // 从Token中获取用户ID
        // TODO: 实现从Token中解析用户ID的逻辑
        Long userId = 1L; // 临时值，实际应从Token中解析
        return adminUserService.changePassword(userId, oldPassword, newPassword);
    }

    @Operation(summary = "更新用户信息", description = "更新管理员用户信息")
    @PutMapping
    public Result<Void> updateUserInfo(@RequestBody AdminUser user) {
        return adminUserService.updateUserInfo(user);
    }
}